package enterprises

class IndustrialSectorController {

	def scaffold = true 
	
	def statistics = {
		if (!params.id) {
			redirect(action:'list')
		}
		
		def industrialSector = IndustrialSector.get(params.id);
		
		def enterprisesStat = IndustrialSector.executeQuery("select  e.industrialSector.name as sector, count(e.id), " +
												"sum(e.countWorkers), sum(e.manCount), sum(e.womenCount), sum(e.itrCount), " +
												 "sum(summaryArea), sum(freeArea), sum(busyArea), sum(possibleBuildingArea) from Enterprise as e "										
												+ "where e.industrialSector.id = :sectorId "
												+ "group by e.industrialSector.name", [sectorId:params.id as Long]								
												);
		def ownershipStat = IndustrialSector.executeQuery("select e.typeOwnership.name, count(e.id) " +
												"from Enterprise as e "
												+ "where e.industrialSector.id = :sectorId "
												+ "group by e.industrialSector, e.typeOwnership.name", [sectorId:params.id as Long]
												);
		def providersStat = IndustrialSector.executeQuery("select  p.typeProvider.name, count(e.id) from Enterprise as e " +
			"join e.providers as p "
		   + "where e.industrialSector.id = :sectorId "
		   + "group by e.industrialSector, p.typeProvider.name", [sectorId:params.id as Long]
		   );
	   	def consumersStat = IndustrialSector.executeQuery("select c.typeConsumer.name, count(e.id) from Enterprise as e " +
		   "join e.productions as p "
		   + "join p.consumer as c "
		   + "where e.industrialSector.id = :sectorId "
		   + "group by e.industrialSector, c.typeConsumer.name", [sectorId:params.id as Long]
		   );
	  
	  	[enterprisesStat:enterprisesStat, providersStat:providersStat, consumersStat:consumersStat,
			  industrialSector:industrialSector, ownershipStat:ownershipStat];
	}  

	@Override
	public String applicationName() {
		"Industrial sectors";
	}	
	
	 
}
